package com.gdd.videos.mini_api.controller;

import com.gdd.videos.common.common.GddResult;
import com.gdd.videos.common.util.MD5Utils;
import com.gdd.videos.mini_api.BasicController;
import com.gdd.videos.pojo.User;
import com.gdd.videos.service.UserService;
import com.gdd.videos.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;


/**
 * @author zhangh     
 * @version V1.0.0
 * @projectName parent
 * @title     LoginController   
 * @package    com.gdd.videos.mini_api.controller  
 * @date   2019/9/2 17:28  
 * @explain
 */
@Api(value = "微信端注册登录接口", tags = "微信端注册和登录的Controller")
@RestController
@Slf4j
public class LoginController extends BasicController {

    @Autowired
    private UserService userService;


    @ApiOperation(value = "用户注册", notes = "用户注册的接口")
    @PostMapping("/regist")
    public GddResult regist(@RequestBody User user) throws Exception {

        // 1.判断用户名或者密码是否为空
        if (user == null || StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return GddResult.errorMsg("用户名和密码不能为空");
        }

        // 2.判断用户名是否存在
        boolean flag = userService.queryUsernameIsExist(user.getUsername());
        if (flag) {

            // 如果已经存在,返回错误信息
            log.error("LoginController===> registError: username is exist");
            return GddResult.errorMsg("该用户名已存在");
        } else {
            // 3.保存用户注册信息
            user.setNickname(user.getUsername());
            user.setPassword(MD5Utils.getMD5Str(user.getPassword()));
            user.setFansCounts(0);
            user.setFollowCounts(0);
            user.setReceiveLikeCounts(0);
            userService.saveUser(user);
        }

        // 返回信息时不要将密码返回!
        user.setPassword("");
        UserVo userVo = setRedisUserSession(user);

        return GddResult.ok(userVo);
    }

    /**
     * 将用户session存入redis中
     * @param user
     * @return
     */
    private UserVo setRedisUserSession(@RequestBody User user) {
        // 保存会话到redis
        String uniqueToken = UUID.randomUUID().toString();
        // 设置三十分钟自动过时
        redis.set(USER_REDIS_SESSION + ":" + user.getId(), uniqueToken, 1000 * 60 * 30);

        // 返回user信息
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        userVo.setUserToken(uniqueToken);
        return userVo;
    }


    @ApiOperation(value = "用户登录", notes = "用户登录的接口")
    @PostMapping("/login")
    public GddResult login(@RequestBody User user) throws Exception {

        log.info("LoginController===> registRequest: RequestBody: " + user);

        // 1.判断用户名或者密码是否为空
        if (user == null || StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            log.error("LoginController===> registError: user or username or password has null!");
            return GddResult.errorMsg("用户名和密码不能为空...");
        }

        // 2. 判断用户是否存在,账号密码是否正确
        User resultUser = userService.findByUserName(user.getUsername());

        if (resultUser == null) {

            // 如果用户不存在
            return GddResult.errorMsg("该用户不存在");

        } else if (!MD5Utils.getMD5Str(user.getPassword()).equals(resultUser.getPassword())) {
            // 如果密码不正确
            return GddResult.errorMsg("密码错误,请重新输入");

        } else {
            UserVo userVo = setRedisUserSession(resultUser);
            return GddResult.ok(userVo);
        }

    }

    @ApiOperation(value = "用户注销",notes = "用户登出的接口")
    @ApiImplicitParam(name = "userId",value = "登出用户id",required = true,
                    dataType = "String",paramType = "query")
    @PostMapping("/logout")
    public GddResult logout(String userId){
        System.out.println(userId);
        redis.del(USER_REDIS_SESSION+":"+userId);
        return GddResult.ok();
    }

}
